<?php

namespace console\controllers;

use admin\models\CaseGalleries;
use admin\models\Cases;
use admin\models\Categories;
use admin\models\Products;
use ijony\helpers\File;
use ijony\helpers\Image;
use Yii;
use yii\console\Controller;

/**
 * Data
 *
 * @package console\controllers
 */
class CasesController extends Controller
{

    /**
     * 数据修复
     */
    public function actionImport()
    {
        $folder = Yii::getAlias('@static/');
        $files = glob($folder . "tmp/*");

        $cases = [];
        foreach($files as $file){
            $info = pathinfo($file);
            $params = explode("-", $info['filename']);
            $file = str_replace($folder, "", $file);

            $category = Categories::find()->where(['name' => $params[4]])->one();
            if(!$category){
                echo $file . ' no category';
                die();
            }

            $product = Products::find()->where(['category_id' => $category->id, 'name' => strtoupper($params[0])])->one();
            if(!$product){
                echo $file . ' no product';
                die();
            }

            $key = md5($params[1]);

            if(isset($cases[$key])){
                $cases[$key]['gallery'][] = $file;
                $cases[$key]['product'][] = $product->id;
            }else{

                $cases[$key] = [
                    'name' => $params[1],
                    'age' => $params[3],
                    'description' => $params[2],
                    'developer' => $params[6],
                    'preview' => $file,
                    'gallery' => [],
                    'product' => [
                        $product->id,
                    ],
                ];
            }
        }

        foreach($cases as $case){
            $fileExt = pathinfo($case['preview'], PATHINFO_EXTENSION);

            $preview = Image::copyImg($case['preview']);
            $model = new Cases([
                'name' => $case['name'],
                'developer' => $case['developer'],
                'age' => $case['age'],
                'description' => $case['description'],
                'product_ids' => $case['product'],
                'preview' => $preview,
            ]);

            $model->save();

            foreach($case['gallery'] as $gallery){
                $file = Image::copyImg($gallery);
                (new CaseGalleries(['case_id' => $model->id, 'file' => $file]))->save();
            }
        }
    }
}